package com.typhoon.extend.util.encrypt;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SHA1Util {

    private static final Logger logger = LoggerFactory.getLogger(SHA1Util.class);

    public final static String Sha1(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("sha-1");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            logger.error("系统异常",e);
            return null;
        }
    }
    
    public static String generateCardGetedSignature(String[] params){
        String signature = "";
        if(null==params || params.length == 0){
            return null;
        }
        List<String> list = new ArrayList<String>();
        for (String str : params) {
            if (StringUtils.isNotBlank(str)) {
                list.add(str);
            }
        }
        params = (String[]) list.toArray(new String[list.size()]);
        Arrays.sort(params);
        signature = SHA1Util.Sha1(StringUtils.join(params));
        return signature;
    }
    

    public static void main(String[] args) {
        String[] params = new String[5];
        params[0] = "1";
        params[1] = "2";
        params[2] = String.valueOf(0);
        params[3] = String.valueOf("111111");
        SHA1Util.generateCardGetedSignature(params);
    }

    public static String generateCardGetedSignature(String cardSerial,String token,Long operatorId,long timestamp){
        String signature = "";
        String[] params = new String[4];
        params[0] = cardSerial;
        params[1] = null == token ? "" : token;
        params[2] = String.valueOf(operatorId);
        params[3] = String.valueOf(timestamp);
        signature = generateCardGetedSignature(params);
        if (logger.isInfoEnabled()) {
            logger.info("签名：param[0]:{},param[1]:{},param[2]:{},param[3]:{},signature:{}",
                            new Object[] {params[0], params[1], params[2], params[3], signature});
        }
        return signature;
    }
}
